package com.xyz.study.netty.cases.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * TimeClient
 *
 * @author xyz
 * @version 1.0.0
 * @since 2021/7/2
 */
public class TimeClient {
    public void connect(String host, int port){
        // 配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap bootStrap = new Bootstrap();
            bootStrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(
                                    new StringEncoder(CharsetUtil.UTF_8), // 字符串编码
                                    new DelimiterBasedFrameDecoder(1024, Delimiters.lineDelimiter()), // 以("\n")为结尾分割的 解码器
                                    new StringDecoder(CharsetUtil.UTF_8), // 字符串解码
                                    new TimeClientHandler()
                            );
                        }
                    });
            // Make the connection attempt.
            ChannelFuture channelFuture = bootStrap.connect(host, port).sync();
            // Wait until the connection is closed.
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {

        String host = "127.0.0.1";
        int port = 8080;
        if (null != args && args.length > 0){
            try{
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e){
                e.printStackTrace();
            }
        }
        new TimeClient().connect(host, port);
    }

}
